//index.js
//获取应用实例
var app = getApp();

/**蓝牙接收数据的处理 **/
Page({
    data:{
      items: [
        { name: 0, value: '转速', checked: true,color:'#1E6D47' },
        { name: 1, value: '电压', checked: true,color:'#2d0af1'},
        { name: 2, value: '电流', checked: true,color:'#f10a0a'},
        { name: 3, value: '相电流', checked: true,color:'#080808'},
      ],
      paras: [
        { "id": 0, "name": "控制器软件版本：",   "value":'',"sendvalue":0,"index": 32760,   "datatype":0,"Comments":''},//控制器型号
        { "id": 1, "name": "控制器软件版本：",   "value":'',"sendvalue":0,"index": 32761,   "datatype":0,"Comments":''},//软件版本号
        { "id": 2, "name": "用户登录密码：",     "value":'',"sendvalue":0,"index": 224,   "datatype":1,"Comments":''},//用户登录密码
      ],
      initflag:false,//读取初始数据标志
      sendreq:false,//发送请求
      learnreq:false,//自学习请求
      idx:0,
      index:0,//偏移地址
      sendvalue:0,
      mscount:0,
      mcutype:'',//控制器型号
      mcuswver:'',//软件版本
      blecode:'',//蓝牙密码
      blenameid:'',//已连蓝牙
      logcheckflag: false,

        viewdata:new Int32Array(16),
        Udc:0,
        Idc:0,
        Rpm: 0,
        Imag:0,
        TmpMos:0,
        TmpMot:0,
        WarnCode:0,

        Udc0:0,
        Idc0:0,
        Rpm0: 0,
        Imag0:0,
        TmpMos0:0,
        TmpMot0:0,

        bleready:true,
        connecttips:'搜索蓝牙控制器',
        canvaswidth:300,
        canvasheigh:300,
        Speedmax:800,
        Udcmax:90,
        Idcmax:60,
        Imagmax:200,
        Speedtmpmax:0,
        Udctmpmax:0,
        Idctmpmax:0,
        Imagtmpmax:0,
        lastTapTime: 0, // 记录上次点击的时间戳
        delay:0,//刷新显示延迟
        newdata:false,//新数据刷新
        Errtip:'告警',

        checked0:true,
        checked1:false,
        checked2:true,
        checked3:true,

        activeNames: ['5'],
        acc:'0V',
        brake:'无',
        PD:'无',
        RD:'无',
        Hspeed:'无',
        Lspeed:'无',
        XunHang:'无',
        FangDao:'无',
        ZuoTong:'无',
        BianCheng:'无',
        ChongDian:'无',
        Gear:'P',
        SpdMod:'低速',
        ABC:'0,0,0'

        
    },
    onLoad: function () {
      // 通过 SelectorQuery 获取 Canvas 节点
      wx.createSelectorQuery()
        .select('#canvas')
        .fields({
          node: true,
          size: true,
        })
        .exec(this.init.bind(this))
    },

    onShow: function () {
      wx.setKeepScreenOn({keepScreenOn: true});//常亮
      this.interval =setInterval(this.updataview, 250);//报文接收处理，300ms周期
      this.interval0 = setInterval(this.viewcurve, 250);//绘制曲线
      this.data.delay = 0;
      // 获取屏幕宽度
    },

    onHide: function () { 
      wx.setKeepScreenOn({keepScreenOn: false});//关闭常亮   
      clearInterval(this.interval);
      clearInterval(this.interval0);
      
    },
    onUnload: function () { 
      wx.setKeepScreenOn({keepScreenOn: false});//关闭常亮   
      clearInterval(this.interval);
      clearInterval(this.interval0);
    },
    // 获取当前页面的名称
    getCurrentPageName() {
      const pages = getCurrentPages(); // 获取页面栈
      const currentPage = pages[pages.length - 1]; // 获取当前页面
      const pagePath = currentPage.route; // 获取当前页面的路径

      // 提取页面名称（路径的最后一部分）
      const pageName = pagePath.split('/').pop();
      return pageName;
    },
    init(res) {
      const width = res[0].width
      const height= res[0].height

      this.data.canvaswidth = width
      this.data.canvasheigh = height
  
      const canvas = res[0].node
      this.ctx = canvas.getContext('2d')
  
      const dpr = wx.getSystemInfoSync().pixelRatio
      canvas.width = width * dpr
      canvas.height = height * dpr
      this.ctx.scale(dpr, dpr)

      this.ctx.clearRect(0, 0,  this.data.canvaswidth, this.data.canvasheigh)//清除画布曲线
   
   

      this.x0 = 60;
      this.y0 = 0;
      this.y1 = 0;
      this.y2 = 0;
      this.y3 = 0;
      this.y4 = 0;
      this.y5 = 0;
      this.y6 = 0;

      this.lastx0=60;
      this.lasty0=this.data.canvasheigh*5/6;
      this.lasty1=this.lasty0
      this.lasty2=this.lasty0
      this.lasty3=this.lasty0
      this.lasty4=this.lasty0
      this.lasty5=this.lasty0
      this.lasty6=this.lasty0

      this.axiscreat();
     

    },
  

  
    drawCar() {

    
      this.x0+=2;
      if ( this.x0+20 >  this.data.canvaswidth) {//画布满，清除当前画布
      
        this.x0 = 60
        // this.y0 = 0
         this.lastx0=60;
       //  this.lasty0=this.data.canvasheigh*3/4;
         this.ctx.clearRect(0, 0,  this.data.canvaswidth, this.data.canvasheigh)//清除画布曲线
        // this.ctx.beginPath();
        // this.ctx.strokeStyle = 'red';
   
     
        if(this.data.Udcmax  < this.data.Udctmpmax*1.1)this.data.Udcmax  = this.data.Udctmpmax*1.1;
        if(this.data.Idcmax  < this.data.Idctmpmax*1.1)this.data.Idcmax  = this.data.Idctmpmax*1.1;
        if(this.data.Imagmax < this.data.Imagtmpmax*1.1)this.data.Imagmax = this.data.Imagtmpmax*1.1;
        if(this.data.Speedmax < this.data.Speedtmpmax*1.1)this.data.Speedmax = this.data.Speedtmpmax*1.1;
 
        this.axiscreat()

      }
     else{

      const curveColor1 = '#1E6D47'; // 第一条曲线的颜色-墨绿
      const curveColor2 = '#2d0af1'; // 第二条曲线的颜色-蓝色
      const curveColor3 = '#f10a0a'; // 第三条曲线的颜色-红色
      const curveColor4 = '#080808'; // 第四条曲线的颜色-黑色
     

      var yzero = this.data.canvasheigh*5/6; 
      
    
      //转速曲线
      if(this.data.items[0].checked==true){
        this.ctx.beginPath();
        this.y0 = yzero - (this.data.Rpm*yzero/this.data.Speedmax);
        if(this.data.Speedtmpmax<this.data.Rpm)
        {
          this.data.Speedtmpmax = this.data.Rpm
        }
        this.ctx.moveTo(this.lastx0,this.lasty0)
        this.ctx.lineTo(this.x0,this.y0)
        this.ctx.strokeStyle = curveColor1;
        this.ctx.lineWidth = 2;
        this.ctx.stroke()
      }



      //母线电压曲线
      if(this.data.items[1].checked==true){
        this.ctx.beginPath();
        this.y1 = yzero - (this.data.Udc*yzero/this.data.Udcmax);
        if(this.data.Udctmpmax<this.data.Udc)
        {
          this.data.Udctmpmax = this.data.Udc
        }
        if(this.x0==62){
          this.lasty1 = this.y1
        }
        this.ctx.moveTo(this.lastx0,this.lasty1)
        this.ctx.lineTo(this.x0,this.y1)
        this.ctx.strokeStyle = curveColor2;
        this.ctx.lineWidth = 2;
        this.ctx.stroke()
      }

      
      //母线电流曲线
      if(this.data.items[2].checked==true){
        this.ctx.beginPath();
        this.y2 = yzero - (this.data.Idc*yzero/this.data.Idcmax);
        if(this.data.Idctmpmax<this.data.Idc)
        {
          this.data.Idctmpmax = this.data.Idc
        }
        if(this.x0==62){
          this.lasty2 = this.y2
        }
        this.ctx.moveTo(this.lastx0,this.lasty2)
        this.ctx.lineTo(this.x0,this.y2)
        this.ctx.strokeStyle = curveColor3;
        this.ctx.lineWidth = 2;
        this.ctx.stroke()
      }

     //电机电流曲线
     if(this.data.items[3].checked==true){
        this.ctx.beginPath();
        this.y3 = yzero - (this.data.Imag*yzero/this.data.Imagmax);
        if(this.data.Imagtmpmax<this.data.Imag)
        {
          this.data.Imagtmpmax = this.data.Imag
        }
        if(this.x0==62){
          this.lasty3 = this.y3
        }
        this.ctx.moveTo(this.lastx0,this.lasty3)
        this.ctx.lineTo(this.x0,this.y3)
        this.ctx.strokeStyle = curveColor4;
        this.ctx.lineWidth = 2;
        this.ctx.stroke()
      }

      this.lastx0=this.x0;
      this.lasty0=this.y0;
      this.lasty1=this.y1;
      this.lasty2=this.y2;
      this.lasty3=this.y3;
      this.lasty4=this.y4;
      this.lasty5=this.y5;
      this.lasty6=this.y6;

     }


   //   var speed;
    //  this.ctx.drawImage(this._img, this.x, 100 , 4, 4)
   
    },

    updataview(){

        if(this.getCurrentPageName()!='index') //判断当前页面是否是gauge，否则关闭周期执行
        {
          clearInterval(this.interval);
          clearInterval(this.interval0);
          return;
        }
        if(app.data.LOGOK==false&& app.data.connected==true)//蓝牙已连接，但是未登录
        {
          this.setData(
            {
              connecttips:'正在登录...',
            });

        }
        else{
          this.setData(
            {
              connecttips:app.data.connecttips,
            });
        }

       this.data.delay++;
       if(this.data.delay>8)
       {
        this.data.delay = 100;
       }
       else{
         app.data.Rebuffi=0;
         return;
       }

        if(app.data.bleopen==false)
        {
          app.data.connecttips = '正在打开蓝牙'
          app.data.bleopen = true
          app.data.blefound = false;//清除蓝牙找到标志
          app.openBluetoothAdapter()
        }
        if(app.data.connected==false && app.data.blefound==true )//蓝牙没连接，但已找到
        {
          app.data.connecttips = '正在连接'
          app.createBLEConnection()//自动连接蓝牙
        }
        if(app.data.connected==true)//已经连接成功
        {
          this.userLog();//用户登录
          if(app.data.LOGOK == false)return;//没有登录，返回
          if(this.data.bleready==true)
          {
            this.revdeal();//接收数据的处理

            app.data.BLE_Txbuff[0]= 0x01
            app.data.BLE_Txbuff[1]= 0x03
            app.data.BLE_Txbuff[2]= 0x03
            app.data.BLE_Txbuff[3]= 0xfe
            app.data.BLE_Txbuff[4]= 0x00
            app.data.BLE_Txbuff[5]= 0x1c
            var crc = app.crc16(app.data.BLE_Txbuff,6);
            app.data.BLE_Txbuff[6]= (crc>>8)&0xFF
            app.data.BLE_Txbuff[7]= (crc)&0xFF
            app.data.Txbuffid = 0;
            app.writeBLECharacteristicValue()
          }
        }
    },

    revdeal(){ 
      app.data.mscount++;
      if(app.data.mscount>40)//确认断连 8秒确认断线
      {
        app.data.mscount = 0;
        app.data.connected=false;//断连，重新连接
      }
   //   app.appendLog('=====');
      if((app.data.Rebuffi == 0)&&(app.data.mscount>20))//接收的数据为空4秒报无应答
      {
        wx.showToast({
          title: '控制器未应答',
          icon: 'none', // 提示框的图标，可选值：'success', 'loading', 'none'（默认值）
          duration: 500, // 提示框显示时间（毫秒），默认值为 1500
          mask: true // 是否显示透明蒙层，避免触摸穿透，可选值：true，false（默认值）
        })
      //  return;
        
      }

      var crc = app.crc16(app.data.BLE_Rebuff,app.data.Rebuffi);
      if(crc==0)//crc校验通过
      {
          this.data.newdata=true;
          for(var i=0;i<14;i++)
          {
            this.data.viewdata[i]= ((app.data.BLE_Rebuff[4*i+3]<<8)+app.data.BLE_Rebuff[4*i+4])+(((app.data.BLE_Rebuff[4*i+5]<<8)+app.data.BLE_Rebuff[4*i+6])<<16)
          }
          app.data.crcerrcnt = 0;

          //this.drawCar()

          if(this.data.viewdata[3]<3*65536)
          {
            this.data.viewdata[9] = 0;
          }
          
          this.setData({
            Udc0     : ((this.data.viewdata[2])>>16)+' V',
            Idc0     :((this.data.viewdata[9])>>16)+' A',
            Rpm0     : (this.data.viewdata[0]>>16)+' rpm',
            Imag0    : (this.data.viewdata[3]>>16)+' A',
            TmpMos0  : (this.data.viewdata[4]>>16)+' ℃',
            TmpMot0  : (this.data.viewdata[5]>>16)+' ℃',
            Udc     : ((this.data.viewdata[2])>>16),
            Idc     :((this.data.viewdata[9])>>16),
            Rpm     : (this.data.viewdata[0]>>16),
            Imag    : (this.data.viewdata[3]>>16),
            TmpMos  : (this.data.viewdata[4]>>16),
            TmpMot  : (this.data.viewdata[5]>>16),
            WarnCode:this.data.viewdata[13]>0?this.data.viewdata[13]:this.data.viewdata[12],
            mcuswver:this.data.mcuswver,
            blenameid: app.data.devicenameid
          });
          var Udclow16=0,Imaglow16=0;
          Udclow16 = this.data.viewdata[2]&0x0FFFF;
          Imaglow16 = this.data.viewdata[3]&0X0FFFF;
          this.data.ChongDian='无'
          this.data.BianCheng='无'
          this.data.ZuoTong='无'
          this.data.FangDao='无'
          this.data.XunHang='无'
          this.data.Lspeed='无'
          this.data.Hspeed='无'
          this.data.RD='无'
          this.data.PD='无'
          this.data.brake='无'

          if((Udclow16&0x8000)>0){//bit15
            this.data.ChongDian='有'
          }
          if((Udclow16&0x4000)>0){//bit14
            this.data.BianCheng='有'
          }
          if((Udclow16&0x2000)>0){//bit13
            this.data.ZuoTong='有'
          }
          if((Udclow16&0x1000)>0){//bit12
            this.data.FangDao='有'
          }
          if((Udclow16&0x0800)>0){//bit11
            this.data.XunHang='有'
          }
          if((Udclow16&0x0400)>0){//bit10
            this.data.Lspeed='有'
          }
          if((Udclow16&0x0200)>0){//bit9
            this.data.Hspeed='有'
          }
          if((Udclow16&0x0100)>0){//bit8
            this.data.RD='有'
          }
          if((Udclow16&0x0080)>0){//bit7
            this.data.PD='有'
          }
          if((Udclow16&0x0040)>0){//bit6
            this.data.brake='有'
          }
          if((Udclow16&0x0007)==0)
          {
            this.data.Gear = 'P'
          }
          if((Udclow16&0x0007)==2)
          {
            this.data.Gear = 'D'
          }
          if((Udclow16&0x0007)==4)
          {
            this.data.Gear = 'R'
          }
          if((Udclow16&0x0018)==0)
          {
            this.data.SpdMod = '低速'
          }
          if(((Udclow16&0x0018)>>3)==1)
          {
            this.data.SpdMod = '中速'
          }
          if(((Udclow16&0x0018)>>3)==2)
          {
            this.data.SpdMod = '高速'
          }


          var accvolt=0,abc=0;
          accvolt = ((Imaglow16&0x0FF)/256*5.0).toFixed(2);//油门电压
          abc = (Imaglow16&0x0700)>>8;
          if(abc==0){
            this.data.ABC = '0,0,0'
          }
          if(abc==1){
            this.data.ABC = '0,0,1'
          }
          if(abc==2){
            this.data.ABC = '0,1,0'
          }
          if(abc==3){
            this.data.ABC = '0,1,1'
          }
          if(abc==4){
            this.data.ABC = '1,0,0'
          }
          if(abc==5){
            this.data.ABC = '1,0,1'
          }
          if(abc==6){
            this.data.ABC = '1,1,0'
          }
          if(abc==7){
            this.data.ABC = '1,1,1'
          }
        
          this.setData({
            acc:accvolt+'V',
            brake:this.data.brake,
            PD:this.data.PD,
            RD:this.data.RD,
            Hspeed:this.data.Hspeed,
            Lspeed:this.data.Lspeed,
            XunHang:this.data.XunHang,
            FangDao:this.data.FangDao,
            ZuoTong:this.data.ZuoTong,
            BianCheng:this.data.BianCheng,
            ChongDian:this.data.ChongDian,
            Gear:this.data.Gear,
            SpdMod:this.data.SpdMod,
            ABC:this.data.ABC
          });

          
          if(this.data.WarnCode > 0)
          {
            if(this.data.WarnCode==1)this.data.Errtip='过流'
            if(this.data.WarnCode==2)this.data.Errtip='超速'
            if(this.data.WarnCode==3)this.data.Errtip='过压'
            if(this.data.WarnCode==4)this.data.Errtip='钥匙电欠压'
            if(this.data.WarnCode==5)this.data.Errtip='Mos驱动电压异常'
            if(this.data.WarnCode==6)this.data.Errtip='5V电压异常'
            if(this.data.WarnCode==7)this.data.Errtip='角度信号断线'
            if(this.data.WarnCode==8)this.data.Errtip='电机类故障'
            if(this.data.WarnCode==9)this.data.Errtip='电流闭环失败'
            if(this.data.WarnCode==10)this.data.Errtip='欠压'
            if(this.data.WarnCode==11)this.data.Errtip='控制器温度高'
            if(this.data.WarnCode==12)this.data.Errtip='电机过温'
            if(this.data.WarnCode==13)this.data.Errtip='电流传感器异常'
            if(this.data.WarnCode==14)this.data.Errtip='角度干扰'
            if(this.data.WarnCode==15)this.data.Errtip='转把超限'
            if(this.data.WarnCode==16)this.data.Errtip='转把未复位'
            if(this.data.WarnCode==17)this.data.Errtip='电机堵转'
            if(this.data.WarnCode==18)this.data.Errtip='BMS故障'
            if(this.data.WarnCode==19)this.data.Errtip='BMS通讯断'
            if(this.data.WarnCode==21)this.data.Errtip='刹车信号异常'
            if(this.data.WarnCode==23)this.data.Errtip='用户参数异常'
            if(this.data.WarnCode==24)this.data.Errtip='厂家参数异常'
            if(this.data.WarnCode==31)this.data.Errtip='未做自学习'
            if(this.data.WarnCode==33)this.data.Errtip='学习失败'
            if(this.data.WarnCode==98)this.data.Errtip='程序校验失败'
            if(this.data.WarnCode==99)this.data.Errtip='型号校验失败'

            app.data.connecttips='控制器报警: '+ this.data.Errtip
          }
          else
          {
            app.data.connecttips='控制器连接成功！'
          }
          
      }
      else
      {
        app.data.crcerrcnt++;
      }
    },
    viewcurve()
    {
      if(this.data.newdata==false)return;
      this.data.newdata=false
      this.drawCar()
     
    },
    cleancurve: function (e) {
      const currentTime = e.timeStamp;
      const lastTapTime = this.data.lastTapTime;
      const diff = currentTime - lastTapTime;
  
      if (diff < 300) { // 如果两次点击的时间间隔小于 300 毫秒，则认为是双击事件
        this.x0 = 60
       // this.y0 = 0
        this.lastx0=60;
      //  this.lasty0=this.data.canvasheigh*3/4;
        this.ctx.clearRect(0, 0,  this.data.canvaswidth, this.data.canvasheigh)//清除画布曲线
       // this.ctx.beginPath();
       // this.ctx.strokeStyle = 'red';
  
    
       if(this.data.Udcmax  < this.data.Udctmpmax*1.1)this.data.Udcmax  = this.data.Udctmpmax*1.1;
       if(this.data.Idcmax  < this.data.Idctmpmax*1.1)this.data.Idcmax  = this.data.Idctmpmax*1.1;
       if(this.data.Imagmax < this.data.Imagtmpmax*1.1)this.data.Imagmax = this.data.Imagtmpmax*1.1;
       if(this.data.Speedmax < this.data.Speedtmpmax*1.1)this.data.Speedmax = this.data.Speedtmpmax*1.1;

       this.axiscreat()


      }
      this.setData({
        lastTapTime: currentTime // 更新上次点击的时间戳
      });

    },
    /**创建坐标系 */
    axiscreat()
    {
      const curveColor1 = '#1E6D47'; // 第一条曲线的颜色-墨绿
      const curveColor2 = '#2d0af1'; // 第二条曲线的颜色-蓝色
      const curveColor3 = '#f10a0a'; // 第三条曲线的颜色-红色
      const curveColor4 = '#080808'; // 第四条曲线的颜色-黑色

      var zroy = this.data.canvasheigh*5/6
      var yindx;
      var yindx0;
      var ymax;
      //y轴-转速
      if(this.data.items[0].checked==true){
        this.ctx.beginPath();
        this.ctx.moveTo(15,0)
        this.ctx.lineTo(15,this.data.canvasheigh)
        this.ctx.strokeStyle = curveColor1;
        this.ctx.lineWidth = 1;
        this.ctx.stroke()
  
        if(this.data.Speedmax<1000)
        {
          yindx = 200//200rpm一格对应的y偏移
        }
        else if(this.data.Speedmax<2000)
        {
          yindx = 300//300rpm一格对应的y偏移
        }
        else if(this.data.Speedmax<5000)
        {
          yindx = 1000//1000rpm一格对应的y偏移
        }
        else
        {
          yindx = 2000//2000rpm一格对应的y偏移
        }
        ymax = this.data.Speedmax;
        
        this.ctx.fillStyle = curveColor1;
        this.ctx.font = '8px Arial'; // 设置文本字体和大小
        for(var i=0;i<10;i++)
        {
          this.ctx.beginPath();
          this.ctx.moveTo(15,zroy-i*(zroy*yindx/ymax))
          this.ctx.lineTo(15+5,zroy-i*(zroy*yindx/ymax))
          this.ctx.strokeStyle = curveColor1;
          this.ctx.stroke()
  
          if(i>0){
            this.ctx.fillText(yindx*i, 15,zroy-i*(zroy*yindx/ymax)+8); // 在坐标 (x,y) 处绘制文本
          }else{
            this.ctx.fillText(yindx*i, 15,zroy-i*(zroy*yindx/ymax)+8); // 在坐标 (x,y) 处绘制文本
          }
        }
      }
      
      if(this.data.items[1].checked==true){
        //y轴母线电压
        this.ctx.beginPath();
        this.ctx.moveTo(30,0)
        this.ctx.lineTo(30,this.data.canvasheigh)
        this.ctx.strokeStyle = curveColor2;
        this.ctx.stroke()
        if(this.data.Udcmax<100)
        {
          yindx = 20//20一格对应的y偏移
        }
        else
        {
          yindx = 50//50一格对应的y偏移
        }
        ymax = this.data.Udcmax;
        
        this.ctx.fillStyle = curveColor2;
        this.ctx.font = '8px Arial'; // 设置文本字体和大小
        for(var i=0;i<10;i++)
        {
          this.ctx.beginPath();
          this.ctx.moveTo(30,zroy-i*(zroy*yindx/ymax))
          this.ctx.lineTo(30+5,zroy-i*(zroy*yindx/ymax))
          this.ctx.strokeStyle = curveColor2;
          this.ctx.stroke()

          if(i>0){
            this.ctx.fillText(yindx*i, 30,zroy-i*(zroy*yindx/ymax)+8); // 在坐标 (x,y) 处绘制文本
          }else{
            this.ctx.fillText(yindx*i, 30,zroy-i*(zroy*yindx/ymax)+8); // 在坐标 (x,y) 处绘制文本
          }
        }
      }

      if(this.data.items[2].checked==true){
        //y电池电流
        this.ctx.beginPath();
        this.ctx.moveTo(45,0)
        this.ctx.lineTo(45,this.data.canvasheigh)
        this.ctx.strokeStyle = curveColor3;
        this.ctx.stroke()
        if(this.data.Idcmax<110)
        {
          yindx = 20
        }
        else if(this.data.Idcmax<310)
        {
          yindx = 50
        }
        else
        {
          yindx = 100
        }
        ymax = this.data.Idcmax;
        

        this.ctx.fillStyle = curveColor3;
        this.ctx.font = '8px Arial'; // 设置文本字体和大小
        for(var i=0;i<10;i++)
        {
          this.ctx.beginPath();
          this.ctx.moveTo(45,zroy-i*(zroy*yindx/ymax))
          this.ctx.lineTo(45+5,zroy-i*(zroy*yindx/ymax))
          this.ctx.strokeStyle = curveColor3;
          this.ctx.stroke()

          if(i>0){
            this.ctx.fillText(yindx*i, 45,zroy-i*(zroy*yindx/ymax)+8); // 在坐标 (x,y) 处绘制文本
          }else{
            this.ctx.fillText(yindx*i, 45,zroy-i*(zroy*yindx/ymax)+8); // 在坐标 (x,y) 处绘制文本
          }
        } 
      }

     // if(this.data.items[3].checked==true){
        //y轴电机电流
        this.ctx.beginPath();
        this.ctx.moveTo(60,0)
        this.ctx.lineTo(60,this.data.canvasheigh)
        this.ctx.strokeStyle = curveColor4;
        this.ctx.stroke()
        if(this.data.Imagmax<110)
        {
          yindx = 20
        }
        else if(this.data.Imagmax<310)
        {
          yindx = 50
        }
        else
        {
          yindx = 100
        }
        ymax = this.data.Imagmax;
        
        this.ctx.fillStyle = curveColor4;
        this.ctx.font = '8px Arial'; // 设置文本字体和大小
        for(var i=0;i<10;i++)
        {
          this.ctx.beginPath();
          this.ctx.moveTo(60,zroy-i*(zroy*yindx/ymax))
          this.ctx.lineTo(60+5,zroy-i*(zroy*yindx/ymax))
          this.ctx.strokeStyle = curveColor4;
          this.ctx.stroke()

          if(i>0){
            this.ctx.fillText(yindx*i, 60,zroy-i*(zroy*yindx/ymax)+8); // 在坐标 (x,y) 处绘制文本
          }else{
          // this.ctx.fillText(yindx*i, 60,zroy-i*(zroy*yindx/ymax)+8); // 在坐标 (x,y) 处绘制文本
          }
        }
     // }

      //X轴
      this.ctx.beginPath();
      this.ctx.moveTo(60,zroy)
      this.ctx.lineTo(this.data.canvaswidth,zroy)
      this.ctx.strokeStyle = curveColor4;
      this.ctx.stroke()


      this.ctx.fillStyle = '#000000'; // 设置文本颜色为黑色
      this.ctx.font = '10px Arial'; // 设置文本字体和大小
      for(var i=0;i<10;i++)
      {
        this.ctx.beginPath();
        this.ctx.moveTo(60+i*40,zroy-5)
        this.ctx.lineTo(60+i*40,zroy)
        this.ctx.strokeStyle = curveColor4;
        this.ctx.stroke()

        if(i>0){
          this.ctx.fillText(i*5+'秒', 60+i*40-4,zroy+10); // 在坐标 (x,y) 处绘制文本
        }else{
          this.ctx.fillText(i*5, 60+i*40,zroy+10); // 在坐标 (x,y) 处绘制文本
        }
        
      }

    },
    checkboxChange: function (e) {
      console.log('checkbox发生change事件，携带value值为：', e.detail.value)

      let that =this;
      for(var i=0;i<4;i++)
      {
        that.data.items[i].checked = false;
      }
      e.detail.value.forEach(function(element) {
        console.log('当前元素值为：', element);
        that.data.items[element].checked = true;
      });
      this.x0 = 60
      this.lastx0=60;
      this.ctx.clearRect(0, 0,  this.data.canvaswidth, this.data.canvasheigh)//清除画布曲线
      if(this.data.Udcmax  < this.data.Udctmpmax*1.1)this.data.Udcmax  = this.data.Udctmpmax*1.1;
      if(this.data.Idcmax  < this.data.Idctmpmax*1.1)this.data.Idcmax  = this.data.Idctmpmax*1.1;
      if(this.data.Imagmax < this.data.Imagtmpmax*1.1)this.data.Imagmax = this.data.Imagtmpmax*1.1;
      if(this.data.Speedmax < this.data.Speedtmpmax*1.1)this.data.Speedmax = this.data.Speedtmpmax*1.1;
      this.axiscreat()
 
  
    },

    //折叠面板
    onChange(event) {
      this.setData({
        activeNames: event.detail,
      });
    },
    //蓝牙搜索
    searchble(){
          wx.showToast({
            title: '重新搜索连接中,若连接超时请重上钥匙电',
            icon: 'none', // 提示框的图标，可选值：'success', 'loading', 'none'（默认值）
            duration: 5000, // 提示框显示时间（毫秒），默认值为 1500
            mask: true // 是否显示透明蒙层，避免触摸穿透，可选值：true，false（默认值）
          })

          
          if((app.data.blefound  == true)||(app.data.connected ==true))
          {
            app.closeBLEConnection();
          }
          app.data.blefound  = false;
          app.data.connected = false;
          app.data.bleopen   =false;

          app.data.LOGOK = false;//重新登录
          this.data.logcheckflag = false;
          this.data.idx = 0;
      
    },

    userLog(){//用户登录界面
        if(app.data.LOGOK ==false)//未登录
        {
          app.data.mscount++;
          if(app.data.mscount>20)//确认断连 5秒确认断线
          {
            app.data.mscount = 0;
            app.data.connected=false;//断连，重新连接
            return;//返回
          }

          if((app.data.Rebuffi>6) && (app.data.BLE_Rebuff[1]==3))//读数据应答
          {
            var crc = app.crc16(app.data.BLE_Rebuff,app.data.Rebuffi);
            if(crc==0)//crc校验通过
            {
               var Updatapara = this.data.paras;
               var idupdata   = this.data.idx;
               if(idupdata== 0)//控制器型号
               {
                  var array = new Uint8Array(256);
                  for(var i=3;i<app.data.BLE_Rebuff[2]+3;i++)
                  {
                    array[i-3] = app.data.BLE_Rebuff[i];
                  }

                  var subArray = array.slice(0, app.data.BLE_Rebuff[2]);//截取读取长度的数据
                  Updatapara[idupdata].value = String.fromCharCode.apply(null, subArray);//数组转字符串

                  let str = Updatapara[idupdata].value
                  let cleanedStr = str.replace(/[^a-zA-Z0-9_]/g, "");//非字母、数字、下划线 都去除
                  this.data.mcutype  = cleanedStr;
                  app.data.ptype = cleanedStr; // 同步到全局app.data

                  if(cleanedStr.length>12)//第一次读取这个数据偶尔出现问题，加个长度条件，不满足就重新读取。
                  {
                    this.data.idx++;//读取下一个
                 
                    this.setData({
                      mcutype:this.data.mcutype,
                    });
                  }
                }

               if(idupdata== 1)//版本号
               {
                  var array = new Uint8Array(256);
                  for(var i=3;i<7;i++)
                  {
                    array[i-3] = app.data.BLE_Rebuff[i];
                  }
                  var subArray = array.slice(0, 4);
                  Updatapara[idupdata].value = String.fromCharCode.apply(null, subArray);//数组转字符串
               // Updatapara[idupdata].value = String.fromCharCode.apply(null, app.data.BLE_Rebuff);//数组转字符串
                  this.data.mcuswver = Updatapara[idupdata].value;
                  app.data.mcuswver = Updatapara[idupdata].value; // 同步到全局app.data
                  this.data.idx++;//读取下一个
                

                  this.setData({
                    mcuswver:this.data.mcuswver,
                  });
                }
                if(idupdata == 2)//蓝牙密钥
                {
                  this.data.viewdata[this.data.idx] = ((app.data.BLE_Rebuff[3]<<8)+app.data.BLE_Rebuff[4])+(((app.data.BLE_Rebuff[5]<<8)+app.data.BLE_Rebuff[6])<<16)//组合值
                  Updatapara[idupdata].sendvalue =  this.data.viewdata[idupdata];
                  Updatapara[idupdata].value = Updatapara[idupdata].sendvalue;
                  if(Updatapara[idupdata].datatype == 0)//IQ16
                  {
                    Updatapara[idupdata].value = (Updatapara[idupdata].sendvalue/65536).toFixed(1) //显示值
                  }
                  this.data.blecode = Updatapara[idupdata].value
                  this.data.idx++;//读取下一个
                }
                
                app.data.crcerrcnt = 0;
            }
            else{
              app.data.crcerrcnt++;
            }
          }

          app.data.Rebuffi = 0;//清零接收
          if(this.data.idx<this.data.paras.length)//应答的参数，小于当前元素个数
          {//发送当前下标读取数据指令
            
            var Updatapara = this.data.paras;
            var addr = Updatapara[this.data.idx].index;//读取的偏移地址,注意这个是excel表中的行数
         
            app.data.BLE_Txbuff[0]= 0x01
            app.data.BLE_Txbuff[1]= 0x03
            app.data.BLE_Txbuff[2]= ((addr-2)*2)>>8;//高8位地址
            app.data.BLE_Txbuff[3]= ((addr-2)*2)&0x00FF;//低8位地址
      
            app.data.BLE_Txbuff[4]= 0x00
            app.data.BLE_Txbuff[5]= 15//读取个数
          
            

         

            var crc = app.crc16(app.data.BLE_Txbuff,6);
            app.data.BLE_Txbuff[6]= (crc>>8)&0xFF
            app.data.BLE_Txbuff[7]= (crc)&0xFF

            app.data.Txbuffid = 0;
            app.writeBLECharacteristicValue()
          }
          else{//初始化已经完成

            app.data.Rebuffi = 0;
            this.data.initflag=true;

            if(this.data.blecode==0)//未设置密码
            {
              app.data.LOGOK = true;
            }
            else{//密码验证
              if(this.data.logcheckflag==false)
              {
                this.logcheck()
                this.data.logcheckflag=true;
              }
            //  
             // app.data.LOGOK = true;
            }
          }  
        }
    },

    logcheck(){//密码输入校验
      let that = this;
      wx.showModal({
        title: '请输入：用户蓝牙密码',
        content: '',
        showCancel: true,
        confirmText: '确定',
        cancelText: '取消',
        editable:true,
        type: 'number',
        success: function (res) {
          if (res.confirm) {
         //   app.data.LOGOK = true;
            // 在这里可以处理用户输入的数值
            var parsedFloat = parseFloat(res.content);
            var parsedInt = parseInt(res.content);
            if (!isNaN(parsedFloat) || !isNaN(parsedInt))
            {
                if(that.data.blecode == parsedInt)//输入密码正确。
                {
                  app.data.LOGOK = true;
                }
                else{
                  that.data.logcheckflag=false;//重新输入
                }
            }
            else{//提示非数字输入
              that.data.logcheckflag=false;//重新输入
            }

          } 
        },
      })//输入弹窗结束
    }

    
})
